/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package net.sf.l2j.gameserver.datatables;

import gnu.trove.TIntObjectHashMap;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javolution.util.FastList;
import javolution.util.FastMap;
import net.sf.l2j.L2DatabaseFactory;
import net.sf.l2j.gameserver.model.L2DropCategory;
import net.sf.l2j.gameserver.model.L2DropData;
import net.sf.l2j.gameserver.model.L2MinionData;
import net.sf.l2j.gameserver.model.L2NpcAIData;
import net.sf.l2j.gameserver.model.L2Skill;
import net.sf.l2j.gameserver.model.base.ClassId;
import net.sf.l2j.gameserver.skills.Formulas;
import net.sf.l2j.gameserver.templates.StatsSet;
import net.sf.l2j.gameserver.templates.chars.L2NpcTemplate;

public class NpcTable
{
	private static Logger _log = Logger.getLogger(NpcTable.class.getName());

	private TIntObjectHashMap<L2NpcTemplate> _npcs;

	public static NpcTable getInstance()
	{
		return SingletonHolder._instance;
	}

	private NpcTable()
	{
		_npcs = new TIntObjectHashMap<L2NpcTemplate>();
		restoreNpcData();
	}

	private void restoreNpcData()
	{
		Connection con = null;

		try
		{
			//-------------------------------------------------------------------
			// NPCs infos
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement;
				statement = con.prepareStatement("SELECT "+ L2DatabaseFactory.getInstance().safetyString(new String[] {"id", "idTemplate", "name", "serverSideName", "title", "serverSideTitle", "class", "collision_radius", "collision_height", "level", "sex", "type", "attackrange", "hp", "mp", "hpreg", "mpreg", "str", "con", "dex", "int", "wit", "men", "exp", "sp", "patk", "pdef", "matk", "mdef", "atkspd", "aggro", "matkspd", "rhand", "lhand", "walkspd", "runspd", "enchant", "dropHerbGroup"}) + " FROM npc");
				ResultSet npcdata = statement.executeQuery();

				fillNpcTable(npcdata);
				npcdata.close();
				statement.close();
			}
			catch (Exception e) 
			{
				_log.log(Level.SEVERE, "NpcTable: Error creating NPC table.", e);
			}

			//-------------------------------------------------------------------
			// Skills
			try
			{
				PreparedStatement statement = con.prepareStatement("SELECT npcid, skillid, level FROM npc_skills");
				ResultSet npcskills = statement.executeQuery();
				L2NpcTemplate npcDat = null;
				L2Skill npcSkill = null;

				while (npcskills.next())
				{
					int mobId = npcskills.getInt("npcid");
					npcDat = _npcs.get(mobId);

					if (npcDat == null)
						continue;

					int skillId = npcskills.getInt("skillid");
					int level = npcskills.getInt("level");

					if (npcDat.race == null && skillId == 4416)
					{
						npcDat.setRace(level);
						continue;
					}
					
					npcSkill = SkillTable.getInstance().getInfo(skillId, level);

					if (npcSkill == null)
						continue;

					npcDat.addSkill(npcSkill);
				}

				npcskills.close();
				statement.close();
			} 
			catch (Exception e) 
			{
				_log.log(Level.SEVERE, "NPCTable: Error reading NPC skills table.", e);
			}

			//-------------------------------------------------------------------
			// Droplists
			try 
			{
				PreparedStatement statement2 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[] {"mobId", "itemId", "min", "max", "category", "chance"}) + " FROM droplist ORDER BY mobId, chance DESC");
				ResultSet dropData = statement2.executeQuery();
				L2DropData dropDat = null;
				L2NpcTemplate npcDat = null;

				while (dropData.next())
				{
					int mobId = dropData.getInt("mobId");
					npcDat = _npcs.get(mobId);
					if (npcDat == null)
					{
						_log.severe("NpcTable: No npc correlating with id : " + mobId);
						continue;
					}
					dropDat = new L2DropData();

					dropDat.setItemId(dropData.getInt("itemId"));
					dropDat.setMinDrop(dropData.getInt("min"));
					dropDat.setMaxDrop(dropData.getInt("max"));
					dropDat.setChance(dropData.getInt("chance"));

					int category = dropData.getInt("category");

					npcDat.addDropData(dropDat, category);
				}

				dropData.close();
				statement2.close();
			} 
			catch (Exception e) 
			{
				_log.log(Level.SEVERE, "NPCTable: Error reading NPC dropdata. ", e);
			}

			//-------------------------------------------------------------------
			// Learn skills
			try 
			{
				PreparedStatement statement3 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[] {"npc_id", "class_id"}) + " FROM skill_learn");
				ResultSet learndata = statement3.executeQuery();

				while (learndata.next())
				{
					int npcId = learndata.getInt("npc_id");
					int classId = learndata.getInt("class_id");
					L2NpcTemplate npc = getTemplate(npcId);

					if (npc == null)
					{
						_log.warning("NpcTable: Error getting NPC template ID " + npcId + " while trying to load skill trainer data.");
						continue;
					}

					npc.addTeachInfo(ClassId.values()[classId]);
				}

				learndata.close();
				statement3.close();
			} 
			catch (Exception e) 
			{
				_log.log(Level.SEVERE, "NPCTable: Error reading NPC trainer data.", e);
			}

			//-------------------------------------------------------------------
			// Minions
			try 
			{
				PreparedStatement statement4 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[] {"boss_id", "minion_id", "amount_min", "amount_max"}) + " FROM minions");
				ResultSet minionData = statement4.executeQuery();
				L2MinionData minionDat = null;
				L2NpcTemplate npcDat = null;
				int cnt = 0;

				while (minionData.next())
				{
					int raidId = minionData.getInt("boss_id");
					npcDat = _npcs.get(raidId);
					if (npcDat == null)
					{
						_log.warning("Minion references undefined boss NPC. Boss NpcId: " + raidId);
						continue;
					}
					minionDat = new L2MinionData();					
					minionDat.setMinionId(minionData.getInt("minion_id"));
					minionDat.setAmountMin(minionData.getInt("amount_min"));
					minionDat.setAmountMax(minionData.getInt("amount_max"));
					npcDat.addRaidData(minionDat);
					cnt++;
				}

				minionData.close();
				statement4.close();
				_log.info("NpcTable: Loaded " + cnt + " Minions.");
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "NPCTable: Error loading minion data.", e);
			}
			
			//-------------------------------------------------------------------
			// AIs Attributes & Data
			try
			{
				PreparedStatement statement10 = con.prepareStatement("SELECT * FROM npc_ai_data ORDER BY npc_id");
				ResultSet NpcAIDataTable = statement10.executeQuery();
				L2NpcAIData npcAIDat = null;
				L2NpcTemplate npcDat = null;
				int cont = 0;
				
				while (NpcAIDataTable.next())
				{
					int npc_id = NpcAIDataTable.getInt("npc_id");
					npcDat = _npcs.get(npc_id);
					if (npcDat == null)
					{
						_log.severe("NPCTable: AI Data Error with id : " + npc_id);
						continue;
					}
					npcAIDat = new L2NpcAIData();
					
					npcAIDat.setMinSkillChance(NpcAIDataTable.getInt("min_skill_chance"));
					npcAIDat.setMaxSkillChance(NpcAIDataTable.getInt("max_skill_chance"));
					npcAIDat.setPrimaryAttack(NpcAIDataTable.getInt("primary_attack"));
					npcAIDat.setCanMove(NpcAIDataTable.getInt("can_move"));
					npcAIDat.setShortRangeSkill(NpcAIDataTable.getInt("minrangeskill"));
					npcAIDat.setShortRangeChance(NpcAIDataTable.getInt("minrangechance"));
					npcAIDat.setLongRangeSkill(NpcAIDataTable.getInt("maxrangeskill"));
					npcAIDat.setLongRangeChance(NpcAIDataTable.getInt("maxrangechance"));
					npcAIDat.setSoulShot(NpcAIDataTable.getInt("soulshot"));
					npcAIDat.setSpiritShot(NpcAIDataTable.getInt("spiritshot"));
					npcAIDat.setSpiritShotChance(NpcAIDataTable.getInt("spschance"));
					npcAIDat.setSoulShotChance(NpcAIDataTable.getInt("sschance"));
					npcAIDat.setIsChaos(NpcAIDataTable.getInt("is_chaos"));
					npcAIDat.setClan(NpcAIDataTable.getString("clan"));
					npcAIDat.setClanRange(NpcAIDataTable.getInt("clan_range"));
					npcAIDat.setEnemyClan(NpcAIDataTable.getString("enemy_clan"));
					npcAIDat.setEnemyRange(NpcAIDataTable.getInt("enemy_range"));
					npcAIDat.setAi(NpcAIDataTable.getString("ai_type"));
					//npcAIDat.setBaseShldRate(NpcAIDataTable.getInt("baseShldRate"));
					//npcAIDat.setBaseShldDef(NpcAIDataTable.getInt("baseShldDef"));
					
					npcDat.setAIData(npcAIDat);
					cont++;
				}
				
				NpcAIDataTable.close();
				statement10.close();
				_log.info("NpcAIData: Loaded " + cont + " AIs.");
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "NpcTable: Error reading NpcAIData: " + e.getMessage(), e);
			}
		} 
		finally 
		{
			try { con.close(); } catch (Exception e) {}
		}
	}

	private void fillNpcTable(ResultSet NpcData) throws Exception
	{
		while (NpcData.next())
		{
			StatsSet npcDat = new StatsSet(); 
			int id = NpcData.getInt("id");
			
			assert id < 1000000;

			npcDat.set("npcId", id);
			npcDat.set("idTemplate", NpcData.getInt("idTemplate"));
			int level = NpcData.getInt("level");
			npcDat.set("level", level);
			npcDat.set("jClass", NpcData.getString("class"));

			npcDat.set("baseShldDef", 0);
			npcDat.set("baseShldRate", 0);
			npcDat.set("baseCritRate", 38);

			npcDat.set("name", NpcData.getString("name"));
			npcDat.set("serverSideName", NpcData.getBoolean("serverSideName"));
			npcDat.set("title",NpcData.getString("title"));
			npcDat.set("serverSideTitle",NpcData.getBoolean("serverSideTitle"));
			npcDat.set("collision_radius", NpcData.getDouble("collision_radius"));
			npcDat.set("collision_height", NpcData.getDouble("collision_height"));
			npcDat.set("sex", NpcData.getString("sex"));
			npcDat.set("type", NpcData.getString("type"));
			npcDat.set("baseAtkRange", NpcData.getInt("attackrange"));
			npcDat.set("rewardExp", NpcData.getInt("exp"));
			npcDat.set("rewardSp", NpcData.getInt("sp"));
			npcDat.set("aggroRange", NpcData.getInt("aggro"));
			npcDat.set("rhand", NpcData.getInt("rhand"));
			npcDat.set("lhand", NpcData.getInt("lhand"));
			npcDat.set("baseWalkSpd", NpcData.getInt("walkspd"));
			npcDat.set("enchant", NpcData.getInt("enchant"));
			
			int STR = npcDat.getInteger("str", Formulas.BASENPCSTR);
			int CON = npcDat.getInteger("con", Formulas.BASENPCCON);
			int DEX = npcDat.getInteger("dex", Formulas.BASENPCDEX);
			int WIT = npcDat.getInteger("wit", Formulas.BASENPCWIT);
			int MEN = npcDat.getInteger("men", Formulas.BASENPCMEN);
			int INT = npcDat.getInteger("int", Formulas.BASENPCINT);
			
			// constants, until we have stats in DB
			npcDat.set("baseSTR", STR);
			npcDat.set("baseCON", CON);
			npcDat.set("baseDEX", DEX);
			npcDat.set("baseINT", INT);
			npcDat.set("baseWIT", WIT);
			npcDat.set("baseMEN", MEN);

			// Calculating Stats by using BaseStats (STR, DEX, CON, MEN, WIT, INT) FIXME: NPC stats
			/*if (NpcData.getString("type").equalsIgnoreCase("L2Pet"))
			{*/
				npcDat.set("baseRunSpd", NpcData.getInt("runspd"));
				npcDat.set("basePAtkSpd", NpcData.getInt("atkspd"));
				npcDat.set("baseMAtkSpd", NpcData.getInt("matkspd"));
				npcDat.set("basePAtk", NpcData.getInt("patk"));
				npcDat.set("baseMAtk", NpcData.getInt("matk"));
				npcDat.set("baseMDef", NpcData.getInt("mdef"));
				npcDat.set("basePDef", NpcData.getInt("pdef"));
			/*}
			else
			{
				npcDat.set("baseRunSpd", Formulas.calcNpcMoveBonus(DEX, NpcData.getInt("runspd")));
				npcDat.set("basePAtkSpd", Formulas.calcNpcPatkSpdBonus(DEX, NpcData.getInt("atkspd")));
				npcDat.set("baseMAtkSpd", Formulas.calcNpcMatkSpdBonus(WIT, NpcData.getInt("matkspd")));
				npcDat.set("basePAtk", Formulas.calcNpcPatkBonus(STR, NpcData.getInt("patk"), level));
				npcDat.set("baseMAtk", Formulas.calcNpcMatkBonus(INT, NpcData.getInt("matk"), level));
				npcDat.set("baseMDef", Formulas.calcNpcMdefBonus(MEN, NpcData.getInt("mdef"), level));
				npcDat.set("basePDef", Formulas.calcNpcPdefBonus(NpcData.getInt("pdef"), level));
			}*/
				
			npcDat.set("dropHerbGroup", NpcData.getInt("dropHerbGroup"));
			
			npcDat.set("baseHpMax", Formulas.calcNpcHpBonus(CON, NpcData.getInt("hp")));
			npcDat.set("baseMpMax", Formulas.calcNpcMpBonus(MEN, NpcData.getInt("mp")));
			npcDat.set("baseCpMax", 0);
			
			npcDat.set("baseHpReg", NpcData.getFloat("hpreg")>0?NpcData.getFloat("hpreg"):1.5 + ((level-1)/10.0));
			npcDat.set("baseMpReg", NpcData.getFloat("mpreg")>0?NpcData.getFloat("mpreg"):0.9 + 0.3*((level-1)/10.0));

			L2NpcTemplate template = new L2NpcTemplate(npcDat);

			_npcs.put(id, template);
		}

		_log.config("NpcTable: Loaded " + _npcs.size() + " Npc Templates.");
	}

	public void reloadNpc(int id)
	{
		Connection con = null;

		try
		{
			// save a copy of the old data
			L2NpcTemplate old = getTemplate(id);
			Map<Integer, L2Skill> skills = new FastMap<Integer, L2Skill>();

			if (old.getSkills() != null)
				skills.putAll(old.getSkills());

			FastList<L2DropCategory> categories = new FastList<L2DropCategory>();

			if (old.getDropData() != null)
				categories.addAll(old.getDropData());

			ClassId[] classIds = null;

			if (old.getTeachInfo() != null)
				classIds = old.getTeachInfo().clone();

			List<L2MinionData> minions = new FastList<L2MinionData>();

			if (old.getMinionData() != null)
				minions.addAll(old.getMinionData());

			// reload the NPC base data
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement st = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[] {"id", "idTemplate", "name", "serverSideName", "title", "serverSideTitle", "class", "collision_radius", "collision_height", "level", "sex", "type", "attackrange", "hp", "mp", "hpreg", "mpreg", "str", "con", "dex", "int", "wit", "men", "exp", "sp", "patk", "pdef", "matk", "mdef", "atkspd", "aggro", "matkspd", "rhand", "lhand", "walkspd", "runspd", "enchant", "dropHerbGroup"}) + " FROM npc WHERE id=?");
			st.setInt(1, id);
			ResultSet rs = st.executeQuery();
			fillNpcTable(rs);
			rs.close();
			st.close();

			// restore additional data from saved copy
			L2NpcTemplate created = getTemplate(id);

			for (L2Skill skill : skills.values())
				created.addSkill(skill);

			if (classIds != null)
				for (ClassId classId : classIds)
					created.addTeachInfo(classId);

			for (L2MinionData minion : minions)
				created.addRaidData(minion);
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "NPCTable: Could not reload data for NPC " + id + ": " + e.getMessage(), e);
		}
		finally
		{
			try { con.close(); } catch (Exception e) {}
		}
	}

	// just wrapper
	public void reloadAllNpc()
	{
		_npcs.clear();
		restoreNpcData();
	}

	public void saveNpc(StatsSet npc)
	{
		Connection con = null;
		String query = "";

		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			Map<String, Object> set = npc.getSet();

			String name = "";
			String values = "";

			for (Object obj : set.keySet())
			{
				name = (String)obj;

				if (!name.equalsIgnoreCase("npcId"))
				{
					if (values != "")
						values += ", ";

					values += name + " = '" + set.get(name) + "'";
				}
			}

			query = "UPDATE npc SET " + values + " WHERE id = ?";
			PreparedStatement statement = con.prepareStatement(query);
			statement.setInt(1, npc.getInteger("npcId"));
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.warning("NPCTable: Could not store new NPC data in database: " + e);
		} 
		finally 
		{
			try { con.close(); } catch (Exception e) {}
		}
	}

	public void replaceTemplate(L2NpcTemplate npc)
	{
		_npcs.put(npc.npcId, npc);
	}

	public L2NpcTemplate getTemplate(int id)
	{
		return _npcs.get(id);
	}

	public L2NpcTemplate getTemplateByName(String name)
	{
		for (Object npcTemplate : _npcs.getValues())
			if (((L2NpcTemplate)npcTemplate).name.equalsIgnoreCase(name))
				return (L2NpcTemplate) npcTemplate;

		return null;
	}

	public L2NpcTemplate[] getAllOfLevel(int lvl)
	{
		List<L2NpcTemplate> list = new FastList<L2NpcTemplate>();

		for (Object t : _npcs.getValues())
			if (((L2NpcTemplate)t).level == lvl)
				list.add((L2NpcTemplate) t);

		return list.toArray(new L2NpcTemplate[list.size()]);
	}

	public L2NpcTemplate[] getAllMonstersOfLevel(int lvl)
	{
		List<L2NpcTemplate> list = new FastList<L2NpcTemplate>();

		for (Object t : _npcs.getValues())
			if (((L2NpcTemplate)t).level == lvl && "L2Monster".equals(((L2NpcTemplate)t).type))
				list.add((L2NpcTemplate) t);

		return list.toArray(new L2NpcTemplate[list.size()]);
	}

	public L2NpcTemplate[] getAllNpcStartingWith(String letter)
	{
		List<L2NpcTemplate> list = new FastList<L2NpcTemplate>();

		for (Object t : _npcs.getValues())
			if (((L2NpcTemplate)t).name.startsWith(letter) && "L2Npc".equals(((L2NpcTemplate)t).type))
				list.add((L2NpcTemplate) t);

		return list.toArray(new L2NpcTemplate[list.size()]);
	}
	
	public L2NpcTemplate[] getAllNpcOfClassType(String classType)
	{
		List<L2NpcTemplate> list = new FastList<L2NpcTemplate>();

		for (Object t : _npcs.getValues())
			if (classType.equals(((L2NpcTemplate)t).type))
				list.add((L2NpcTemplate) t);

		return list.toArray(new L2NpcTemplate[list.size()]);
	}
	
	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder
	{
		protected static final NpcTable _instance = new NpcTable();
	}
}